
local error= error

require "lanes"

local _prepare= lanes.prepare

---=== Cancel/resurrect + timeout test ===---

-- 'count' is given as a global, which is incremented at each start
-- of the lane.
--
local glob= { count=0 }

while true do
    local old_count= glob.count
    local h= _prepare"*" { cancelstep=true, G= glob } (
                function()
                    count= count+1
                    io.stderr:write( "inside: ".. count.."\n" )
                    while count<5 do end
                    return count
                end ) ()

    io.stderr:write( "state: ".. h.state .."\n" )
    io.stderr:write( "count: ".. glob.count .."\n" )
    io.stderr:write( "state: ".. h.state .."\n" )

    local a= h:results( 2.0 )   -- secs
    if not a then
        h:cancel()  -- just a request, asynchronous
        a,glob= h:results( 2.0 )    -- returns when cancel got through

        assert( h.state == "cancelled" )
        assert( a == nil )
        assert( type(glob) == "table" )

        -- Only 'count' should be there (no stdlibs)
        for k,v in pairs(glob) do 
            if k~="count" then
                print(k,v) 
                error "Stdlib namespace leakage?"
            end
        end
    end
    
    if not a then
        io.stderr:write( "timeout!\n" )
        assert( type(glob)=="table" )
        assert( glob.count == old_count+1 )
    else
        io.stderr:write( "returned: "..a.."\n" )
        assert( a==5 )
        break
    end
end
